'use strict';

const {port, static_path} = require('../config/index');
const gulp = require('gulp'),
  gulpLoadPlugins = require('gulp-load-plugins');

const browserSync = require('browser-sync'); // 浏览器自动刷新插件
const $G = gulpLoadPlugins(); // 自动加载已安装gulp插件

const webpack = require('webpack');
const webpackConfig = require('../webpack.config');

// gulp 监听目录不带 './' 可以对新建文件也进行监听，不用重启gulp脚本
const scss_src_path = ['src/scss/*.scss'],
  es_src_path = ['src/es/*.js'],
  es_watch_path=['src/es/**/*.js'],
  scss_watch_path=['src/scss/**/*.scss'],
  static_dist_path = static_path,
  map_dist_path = 'maps/',
  njk_watch_path = ['views/**/*.html', 'views/**/*.njk'];

// browserSync 监听本地服务器
gulp.task('server', ['nodemon'], () => {
  browserSync.init({
    proxy: 'localhost:' + port,
    port: port + 1,
    ui: {
      port: port + 2
    }
  });
});

// 启动本地服务器
gulp.task('nodemon', callback => {
  let called = false;
  $G.nodemon({
    script: './bin/www',
    ext: 'js',
    ignore: ['public/', 'src/'], // 静态资源修改不重启服务器
    env: {NODE_ENV: 'development'}
  }).on('start', () => {
    if (!called) {
      called = true;
      callback();
    }
  });
});

// js 处理, babel
gulp.task('es6', function() {
  console.log('es6');
  gulp.src(es_src_path).
    pipe($G.changed(static_dist_path + 'js', {extension: '.js'})).
    pipe($G.sourcemaps.init()).
    pipe($G.babel()).
    pipe($G.uglify()).
    pipe(
      $G.rename({
        dirname: 'js',
        suffix: '.min'
      })
    ).
    pipe($G.sourcemaps.write(map_dist_path)).
    pipe(gulp.dest(static_dist_path, {mode: '0777'})).
    pipe(browserSync.stream());
});
// scss 处理
gulp.task('sass', function() {
  gulp.src(scss_src_path)
  // .pipe($G.changed(static_dist_path + 'css', { extension: '.css' }))
    .pipe($G.sourcemaps.init()).
    pipe($G.sass.sync({outputStyle: 'expanded'})).
    on('error', $G.sass.logError).
    pipe(
      $G.autoprefixer({
        browsers: [
          'iOS >= 8',
          'Firefox >= 20',
          'Android > 4.4'
        ],
        cascade: true, //是否美化属性值
        remove: true //是否去掉不必要的前缀
      })
    ).
    pipe($G.cleanCss({debug: true}, (details) => {
      console.log(`${details.name}: ${details.stats.originalSize}`);
      console.log(`${details.name}: ${details.stats.minifiedSize}`);
    })).
    pipe(
      $G.rename({
        dirname: 'css',
        suffix: '.min'
      })
    ).
    pipe($G.sourcemaps.write(map_dist_path)).
    pipe(gulp.dest(static_dist_path, {mode: '0777'})).
    pipe(browserSync.stream());
});

// 监听静态资源
gulp.task('watch', () => {
  // 编译javascript
  gulp.watch(es_watch_path, ['es6','webpack']);
  // 编译scss
  gulp.watch(scss_watch_path, ['sass']);
  // 模板编译
  gulp.watch(
    njk_watch_path
    // , ['njk']
  ).on('change', browserSync.reload);
});

//webpack 打包
gulp.task('webpack',function(callback) {
  webpack(webpackConfig,function(err, stats) {
    if(err){
      throw new $G.util.PluginError('webpack',err);
    }
    $G.util.log('[webpack]',stats.toString());
    typeof callback === 'function' && callback();
  });
});
gulp.task('dev', ['server', 'watch']);
module.export = gulp;